package controller

import (
	"Bluebell/common/resp"
	"Bluebell/common/util"
	"Bluebell/logic"
	"Bluebell/models"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"net/http"
)

func RegisterHandler(context *gin.Context) {
	//获取参数
	p := new(models.ParamsSignUp)
	if err := context.ShouldBindJSON(p); err != nil {
		zap.L().Error("Register with invalid params", zap.Error(err))

		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			resp.ResponseErrorWithMsg(context, resp.CodeInvalidParams, err.Error())
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"msg": errs.Translate(util.Trans),
		}) //翻译错误
		return
	}
	//处理
	if err := logic.Register(p); err != nil {
		zap.L().Error("Register failed", zap.Error(err))
		resp.ResponseErrorWithMsg(context, resp.CodeServerBusy, "register fail")
		return
	}
	//返回响应
	resp.ResponseSuccess(context, nil)
}

func LoginHandler(context *gin.Context) {
	p := new(models.ParamsLogin)
	if err := context.ShouldBindJSON(p); err != nil {
		zap.L().Error("Login with invalid params", zap.Error(err))

		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			resp.ResponseErrorWithMsg(context, resp.CodeInvalidParams, err.Error())
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"msg": errs.Translate(util.Trans),
		}) //翻译错误
		return
	}
	user, err := logic.Login(p)
	if err != nil {
		zap.L().Error("Login failed", zap.Error(err))
		resp.ResponseError(context, resp.CodeInvalidPassword)
		return
	}
	//返回响应
	resp.ResponseSuccess(context, gin.H{
		"user_id":   user.UserID,
		"user_name": user.UserName,
		"tokne":     user.Token,
	})
}
